package _11_整理题目._7_查找排序;

import org.junit.Test;

import java.util.Arrays;

public class _07_kmp字符串匹配 {

    @Test
    public void main() {
        String pattern = "aaaa";
        String str = "alb1albanialbaalbaniarfgh";
        int[] next = match(pattern);
        System.out.println(Arrays.toString(next));

        KMPSearch(str, pattern, next);
    }

    public int[] match(String pattern) {
        int[] next = new int[pattern.length()];
        next[0] = 0;
        int j = 0;
        for (int i=1; i < next.length; i++) {
            while (pattern.charAt(i) != pattern.charAt(j) && j>0) {
                j = next[j-1];
            }
            if (pattern.charAt(i) == pattern.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public void KMPSearch(String str1, String str2, int[] next) {
        for (int i = 0, j = 0; i < str1.length(); i++) {
            while (j>0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }
            System.out.println(j);
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {
                System.out.println("Found at: " + (i-j+1));
                return;
            }
        }
        System.out.println("Not found");
    }

}
